package api

import (
	"context"
	"encoding/base64"
	"github.com/wailsapp/wails/v2/pkg/runtime"
	"io/ioutil"
	"myproject/backend/types"
	"myproject/backend/utils"
	"os"
	"path/filepath"
)

type FileSystem struct {
	Ctx context.Context
}

func NewFileSystem() *FileSystem {
	return &FileSystem{}
}

// GetFilesInDirectory 获取指定目录中的文件列表
func (f *FileSystem) GetFilesInDirectory(dirPath string) types.FileInfoResp {
	res := types.FileInfoResp{}
	entries, err := os.ReadDir(dirPath)
	if err != nil {
		res.Code = types.FAIL
		res.Msg = err.Error()
		return res
	}
	var files []types.FileInfo
	for _, entry := range entries {
		info, err := entry.Info()
		if err != nil {
			continue
		}
		files = append(files, types.FileInfo{
			Name:     entry.Name(),
			Path:     filepath.Join(dirPath, entry.Name()),
			IsDir:    entry.IsDir(),
			Size:     info.Size(),
			Modified: info.ModTime().String(),
		})
	}
	res.Code = types.SUCCESS
	res.Data = files
	return res
}

// OpenDirectoryDialog 打开文件夹选择对话框
func (f *FileSystem) OpenDirectoryDialog() (string, error) {
	file, err := runtime.OpenFileDialog(f.Ctx, runtime.OpenDialogOptions{
		Title: "选择txt文件",
		Filters: []runtime.FileFilter{
			{
				DisplayName: "Text Files (*.txt)",
				Pattern:     "*.txt",
			},
		},
	})
	if err != nil {
		return "", err
	}
	return file, nil
}

func (f *FileSystem) ReadTxtFile(filePath string) types.FileContentResp {
	content, err := ioutil.ReadFile(filePath)
	response := types.FileContentResp{}
	if err != nil {
		response.Code = types.FAIL
		response.Msg = err.Error()
		return response
	}
	response.Code = types.SUCCESS
	response.Data = types.FileContent{
		Name:    filepath.Base(filePath),
		Path:    filePath,
		Content: string(content),
	}
	return response
}

//func SaveObjFile(ctx *runtime.Context, objContent string) error { // 获取public目录路径
//	publicDir, err := runtime.GetAssetsDir(ctx)
//	if err != nil {
//		return err
//		// 构建目标文件路径
//	}
//	targetPath := filepath.Join(publicDir, "model", "model.obi") // 创建目录(如果不存在)
//	err = os.MkdirAll(filepath.Dir(targetPath), os.ModePerm)
//	if err != nil {
//		return err
//	}
//	return os.WriteFile(targetPath, []byte(objContent), os.ModePerm)
//}

// UploadFile 上传文件
func (f *FileSystem) UploadFile(fileBytes []byte) types.FileUploadResp {
	resp := types.FileUploadResp{}
	err := utils.HttpUploadRequest(fileBytes, &resp)
	if err != nil {
		resp.Code = types.FAIL
		resp.Msg = err.Error()
	}
	resp.Code = types.SUCCESS
	return resp
}

func (f *FileSystem) GetImage(path string) string {
	data, err := os.ReadFile(path)
	if err != nil {
		return ""
	}
	return base64.StdEncoding.EncodeToString(data)
}
